<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta
			name="viewport"
			content="width=device-width,initial-scale=1.0,user-scalable=no,maximum-scale=1,minimum-scale=1"
		/>
		<title>RiverSplit</title>
		<link
			href="https://cdn.bootcdn.net/ajax/libs/openlayers/4.6.5/ol.css"
			rel="stylesheet"
		/>
		<style>
			html,
			body {
				height: 100%;
				width: 100%;
			}
			.map {
				height: 100%;
				width: 100%;
			}
			.ol-btn {
				width: auto !important;
				cursor: pointer;
				padding: 5px !important;
			}
			.box {
				top: 77px;
				left: 16px;
			}
		</style>
		<script src="https://cdn.bootcdn.net/ajax/libs/openlayers/4.6.5/ol.js"></script>
	</head>
	<body>
		<div id="map" class="map"></div>
		<div class="ol-control box">
			<button class="ol-btn" id="toggle">toggle</button>
		</div>
	</body>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
	<script>
		const tileLayer = new ol.layer.Tile({
			source: new ol.source.OSM(),
		});
		let vectorLayerGeoJson = null;
		const url = 'http://localhost:3000/RiverSplit.json';
		let map = null;
		$.get(url, (data) => {
			vectorLayerGeoJson = new ol.layer.Vector({
				source: new ol.source.Vector({
					projection: 'EPSG:4326',
					url,
					format: new ol.format.GeoJSON(),
				}),
				style: new ol.style.Style({
					stroke: new ol.style.Stroke({
						color: 'blue',
						width: 2,
					}),
				}),
			});
			map = new ol.Map({
				target: 'map',
				view: new ol.View({
					// center: ol.proj.fromLonLat([120, 30]),
					center: ol.proj.fromLonLat([112.88868562594098, 23.15542959180226]),
					zoom: 12,
				}),
				layers: [vectorLayerGeoJson],
			});
		});

		// 随机颜色
		function getRandomColor() {
			function random() {
				return Math.ceil(Math.random() * 255);
			}
			return `rgb(${random()}, ${random()}, ${random()})`;
		}

		const toggleBtn = document.querySelector('#toggle');
		toggleBtn.addEventListener('click', (e) => {
			map
				.getLayers()
				.getArray()[0]
				.setStyle(
					new ol.style.Style({
						stroke: new ol.style.Stroke({
							color: getRandomColor(),
							width: 2,
						}),
					})
				);
		});
	</script>
</html>
